package com.jkdl.springboot.service.impl;
import com.jkdl.springboot.exception.BusinessException;
import com.jkdl.springboot.service.BusinessActivityImgService;
import com.jkdl.springboot.service.BusinessActivityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class BusinessActivityImgImpl implements BusinessActivityImgService {

    @Override
    public Map<String, Object> uploadImg(MultipartFile file, HttpServletRequest request) {


        String contentType = file.getContentType();

        String root_fileName = file.getOriginalFilename();
        log.info("上传图片:name={},type={}", root_fileName, contentType);
        //处理图片



        String fileName = file.getOriginalFilename();
        String extentionName = fileName.substring(fileName.lastIndexOf(".")); // 后缀名  2 .jpg
        String newPath = request.getSession().getServletContext().getRealPath("/");     //文件路径

        String newName = System.currentTimeMillis() + extentionName;// 新名    3

        Calendar date = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

        String name = format.format(date.getTime());
        String newMkName = newPath+"/"+name;  //日期文件夹
        File file2 = new File(newMkName);
        //生成日期文件夹    4
        if(!file2.exists()) {
            file2.mkdir();
        }

        String filePath = newMkName  + "/" + newName;// 文件完整路径   5
        File m = new File(request.getSession().getServletContext().getRealPath("/")+"/"+file.getName());
        File file1=new File(filePath);
        boolean flag;
        if(file1.exists()){
            throw new BusinessException("不可上传重复的图片");
        }

        flag = m.renameTo(file1); // 重命名并上传文件    6
        Map<String,Object> map = new HashMap<>();
        if(!flag){
            map.put("fileName",newName);
            map.put("fileUrl", "https://www.mwsong.com"+"/xcximg/"+newName);
            return map;
        }else{
            return null;
        }

    }
}
